package com.xiaobaibai.security.master_login.filter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
public class MyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private String usernameParameter = "username";
    private String passwordParameter = "password";
    private boolean postOnly = true;//是否只处理post请求

    public MyUsernamePasswordAuthenticationFilter() {
        //匹配login路径+指定方法
        super(new AntPathRequestMatcher("/login"));
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

//        System.out.println("过滤器");
//        String str = "";
//        String data = "";
//        BufferedReader br = null;
//        try {
//            br = request.getReader();
//            while ((str = br.readLine()) != null) {
//                data += str;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        Map<String,String> filterLoginData = JSON.parseObject(data, Map.class);
//        request.setAttribute("loginData",filterLoginData);


        String username = request.getParameter(usernameParameter);
        String password = request.getParameter(passwordParameter);
        if (username == null) {
            username = "";
            throw new AuthenticationServiceException("账号不可为空");
        }

        if (password == null) {
            password = "";
            throw new AuthenticationServiceException("密码不可为空");
        }

        username = username.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        this.setDetails(request, authRequest);
        Authentication authenticate=null;
        try {
            authenticate = this.getAuthenticationManager().authenticate(authRequest);
        }catch (Exception e){
            InsufficientAuthenticationException failed = new InsufficientAuthenticationException(e.getMessage(),e);
            try {
                this.unsuccessfulAuthentication(request,response,failed);
            } catch (IOException | ServletException ex) {
                ex.printStackTrace();
            }
        }
        return authenticate;
    }

    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

}
